package com.book.service.impl;

import com.book.dto.BookManageDto;
import com.book.entity.Book;
import com.book.format.Result;
import com.book.format.ResultUtil;
import com.book.page.Page;
import com.book.service.BookService;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Mikey on 2017/6/14.
 */
@Service
public class BookServiceImpl implements BookService {

    private String BOOKMAPPER = "com.book.mapper.BookMapper";

    @Resource
    private SqlSessionTemplate sqlSessionTemplate;

    public Result getBookList(Page page){
        Integer count = sqlSessionTemplate.selectOne(BOOKMAPPER+".selectCount");
        List<BookManageDto> bookManageDtos = sqlSessionTemplate.selectList(BOOKMAPPER+".selectBookList",page);
        Map map = new HashMap();
        map.put("count",count);
        map.put("books",bookManageDtos);
        return ResultUtil.success(map);
    }

    public Result deleteBook(String b_id){
        Map map = new HashMap();
        map.put("b_id",b_id);
        Integer i =  sqlSessionTemplate.delete(BOOKMAPPER+".deleteBook",map);
        return ResultUtil.success(i);
    }

    public Result addOrEditBook(Book book){
        Integer i;
        if("".equals(book.getB_id())){
            book.setB_id(UUID.randomUUID().toString());
            i = sqlSessionTemplate.insert(BOOKMAPPER+".addBook",book);
        }else{
            i = sqlSessionTemplate.update(BOOKMAPPER+".updateBook",book);
        }
        return ResultUtil.success(i);
    }
}
